from PyQt5.QtWidgets import QWidget, QFileDialog
from .Ui_table import Ui_Form2
from PyQt5.QtWidgets import QTableWidgetItem, QHeaderView
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import Qt
from qfluentwidgets import InfoBar, InfoBarPosition
import pandas as pd

class TableInterface(QWidget, Ui_Form2):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.init_table()
        
    def init_table(self):
        self.tableWidget.setBorderVisible(True)
        self.tableWidget.setBorderRadius(8)

        self.tableWidget.setWordWrap(False)
        self.tableWidget.setRowCount(60)
        self.tableWidget.setColumnCount(7)
        
        score_infos = [
            ['张三', '12345678901', '90', '80', '70', '60', '300'],
            ['李四', '12345678901', '90', '100', '70', '60', '300'],
            ['王五', '12345678901', '90', '80', '70', '60', '300'],
            ['赵六', '12345678901', '90', '80', '70', '60', '300'],
            ['周七', '12345678901', '90', '80', '80', '60', '400'],
            ['钱八', '12345678901', '90', '80', '70', '90', '300'],
            ['孙九', '12345678901', '90', '80', '70', '60', '300'],
            ['李十', '12345678901', '90', '80', '70', '60', '300'],
            ['王十一', '12345678901', '100', '80', '70', '60', '300'],
            ['钱十二', '12345678901', '90', '80', '70', '60', '300']
        ]
        
        for i, score_info in enumerate(score_infos):
            for j in range(7):
                item = QTableWidgetItem(score_info[j])
                item.setTextAlignment(Qt.AlignCenter)
                self.tableWidget.setItem(i, j, item)

        self.tableWidget.verticalHeader().hide()
        self.tableWidget.setHorizontalHeaderLabels(['姓名', '学号', '第一题', '第二题', '第三题', '第四题', '总分'])
        self.tableWidget.resizeColumnsToContents()
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableWidget.setSortingEnabled(True)

        self.setStyleSheet("Demo{background: rgb(255, 255, 255)} ")
        # self.resize(735, 760)

    @pyqtSlot()
    def btn_sort_clicked(self):
        print('sort')
        
    def create_success_infoBar(self):
        InfoBar.success(
            title='success',
            content="保存成功！",
            orient=Qt.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            duration=2000,
            parent=self
        )
        
    @pyqtSlot()
    def btn_export_clicked(self):
        # 让用户选择文件夹
        folder_path = QFileDialog.getExistingDirectory(
            self, "选择保存文件夹", ""
        )

        if not folder_path:  # 用户取消了选择
            return

        # 设置默认文件名（可以自定义）
        default_filename = "score_list.xlsx"
        file_path = f"{folder_path}/{default_filename}"

        # 获取表格数据
        rows = self.tableWidget.rowCount()
        cols = self.tableWidget.columnCount()

        # 获取表头
        headers = []
        for i in range(cols):
            headers.append(self.tableWidget.horizontalHeaderItem(i).text())

        # 获取表格内容
        data = []
        for row in range(rows):
            row_data = []
            for col in range(cols):
                item = self.tableWidget.item(row, col)
                if item is not None:
                    row_data.append(item.text())
                else:
                    row_data.append('')
            # 只导出有数据的行（避免导出空行）
            if any(row_data):  # 如果行中有任何非空数据
                data.append(row_data)

        # 创建DataFrame并保存为Excel
        df = pd.DataFrame(data, columns=headers)
        try:
            df.to_excel(file_path, index=False, engine='openpyxl')
            print(f"文件已成功保存到: {file_path}")
            self.create_success_infoBar()
        except Exception as e:
            print(f"保存文件时出错: {e}")